﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Runtime.Serialization;
using System.Xml;
using System.ServiceModel.Channels;

namespace Acando.Dynamics.CRM.Silverlight.Library.Helper
{
    /// <summary>
    /// You have to add this class to generate the CRM authentication header.
    /// Allows Silverlight to consume the web services
    /// </summary>
    public class CrmAuthenticationTokenSerializer : XmlObjectSerializer
    {
        private int _authType;
        private string _organizationName;
        private string _callerId;

        public CrmAuthenticationTokenSerializer(int authType, string organizationName, string callerId)
        {
            _authType = authType;
            _organizationName = organizationName;
            _callerId = callerId;
            if (_callerId == null) 
                _callerId = "00000000-0000-0000-0000-000000000000";
        }

        public override void WriteStartObject(XmlDictionaryWriter writer, Object graph)
        { }

        public override void WriteObjectContent(XmlDictionaryWriter writer, Object graph)
        {
            string authToken = string.Format("<AuthenticationType xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>{0}</AuthenticationType><OrganizationName xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>{1}</OrganizationName><CallerId xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>{2}</CallerId>", _authType, _organizationName, _callerId);
            
            writer.WriteRaw(authToken);
        }

        public override void WriteEndObject(XmlDictionaryWriter writer)
        { }

        public override bool IsStartObject(XmlDictionaryReader reader)
        {
            return true;
        }
        public override Object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
        { return null; }
    }

    public static class CrmMessageHeaderHelper
    {
        public static MessageHeader GenerateAuthHeader(int authenticationType, string organizationName, string callerId)
        {
            return MessageHeader.CreateHeader("CrmAuthenticationToken",
                                                "http://schemas.microsoft.com/crm/2007/WebServices", "",
                                                new CrmAuthenticationTokenSerializer(authenticationType,
                                                                                      organizationName,
                                                                                      callerId));
        }
    }
}
